<template>
  <div class="container">
    <h3>旋转地图</h3>
    <h3>自定义缩放</h3>
    <h4>
      <el-button @click="rotateLeft">👈</el-button>
      <el-button @click="rotateRight">👉</el-button>
      <el-button @click="zoomin">+</el-button>
      <el-button @click="zoomout">-</el-button>
    </h4>
    <div id="vue-openlayers" class="map-x">
      <div id="mouse"></div>
    </div>
  </div>
</template>

<script>
import 'ol/ol.css'
import { Map, View } from 'ol'
import { Tile } from 'ol/layer'
import { XYZ } from 'ol/source'
import * as controls from 'ol/control'
import MousePosition from 'ol/control/MousePosition.js'
import { format } from 'ol/coordinate' // 格式化坐标
export default {
  data() {
    return {
      map: null
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    initMap() {
      let mousePosition = new MousePosition({
          coordinateFormat: coordinate => {
            return format(coordinate, '精度{x}, 纬度{y}', 4) // 格式化坐标
          },
          projection: 'EPSG:4326',
          target: 'mouse'
        })
        // let control1 = new controls.ZoomSlider()

      this.map = new Map({
        target: 'vue-openlayers',
        layers: [
          new Tile({
            source: new XYZ({
              url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7'
            })
          })
        ],
        view: new View({
          projection: 'EPSG:4326',
          center: [116.397411, 39.909186],
          zoom: 10
        }),
        controls: controls.defaults({
          zoom: false, // 禁用缩放控件
          rotate: false, // 禁用旋转
          attribution: false, // 禁用版权信息
        }).extend([
          new controls.ZoomSlider(), // 自定义缩放控件
          new controls.FullScreen(), // 全屏控件
          mousePosition
        ]),
        // controls: [mousePosition, control1]
      })
    },
    rotateLeft() {
      let currentRotation = this.map.getView().getRotation()
      this.map.getView().setRotation(currentRotation + 1)
    },
    rotateRight() {
      let currentRotation = this.map.getView().getRotation()
      this.map.getView().setRotation(currentRotation - 1)
    },
    zoomin() {
      let currentZoom = this.map.getView().getZoom()
      this.map.getView().setZoom(currentZoom + 1)
    },
    zoomout() {
      let currentZoom = this.map.getView().getZoom()
      this.map.getView().setZoom(currentZoom - 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
    width: 840px;
    height: 550px;
    margin: 50px auto;
    border: 1px solid #ccc;
    #vue-openlayers {
      width: 800px;
      height: 420px;
      margin: 0 auto;
      border: 1px solid #42b983;
      position: relative;
      #mouse {
        position: absolute;
        bottom: 10px;
        left: 10px;
        z-index: 10;
        width: 280px;
        height: 32px;
        color: #42b983;
        background-color: #fff;
        vertical-align: baseline;
      }
    }
  }
</style>